<template>
  <Modal v-model="getShowModal" :title="getTitle" width="920" @on-cancel="onCancelFunc" :mask-closable="false">
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
      <Form-item label="用户组名" prop="name">
        <Input v-model="newGroupName" placeholder="请输入用户组名..." :autofocus="true"></Input>
      </Form-item>
    </Form>
    <div style="margin-top: 15px; height: 300px">
      <Transfer :data="allMenus" class="left-table"
      :list-style="listStyle"
      :target-keys="targetKeys"
      :render-format="transferRender"
      :titles="['所有菜单','权限菜单']"
      @on-change="handleChange">
      </Transfer>
      <Table class="right-table" border stripe show-header :columns="tableColumns"
        :data="allOpreates" width="300" height="300" @on-select="onSelected"
        @on-select-all="onSelected"></Table>
    </div>
    <diV slot="footer">
      <Button type="primary" @click="onOkFunc('formValidate')" >提交</Button>
    </diV>
  </Modal>
</template>

<script>
import {KEYS, getFetchedData} from '@/common/constFetchData.js'
import {getAllMenu, getMenuVOList} from '@/api/menu.js'
import {getVO} from '@/common/proto-vo.js'
import {getAllOperates, getOperateAuthVOList, modifyUserGroup, addUserGroup} from '@/api/group.js'

export default {
  // name: 'EditGroupModal',
  // type: 0, 为新建用户组; type: 1, 为修改用户组
  props: ['oldGroupName', 'showModal', 'type', 'oldGroupMenus', 'oldGroupPowers', 'oldGroupId'],
  data () {
    return {
      formValidate: {
        name: ''
      },
      ruleValidate: {
        name: [
          // { required: true, message: '用户组名不能为空', trigger: 'blur' }
        ]
      },
      newGroupId: '',
      newGroupName: '',
      allMenus: [],
      targetKeys: [],
      listStyle: {
        width: '260px',
        height: '300px'
      },
      allOpreates: [],
      tableColumns: [
        {type: 'selection', width: 60, align: 'center'},
        {title: '操作id', key: 'id', width: 90},
        {title: '操作名称', key: 'name'}
      ],
      selected: [],
      defalutSelected: [],
      hasChangeSelected: false
    }
  },
  created () {
    // console.log('module edit create')
    let menus = getFetchedData(KEYS.ALL_MENUS)
    if (menus) {
      this.allMenus = this.createTableData(menus)
    } else {
      getAllMenu().then(data => {
        if (!data) {
          return
        }
        let menuAll = getMenuVOList(data)
        this.allMenus = this.createTableData(menuAll)
      })
    }
    let opts = getFetchedData(KEYS.ALL_OPERATES)
    if (opts) {
      this.allOpreates = opts
    } else {
      getAllOperates().then(d => {
        if (!d) {
          return
        }
        this.allOpreates = getOperateAuthVOList(d)
      })
    }
  },
  methods: {
    onSelected (item) {
      this.hasChangeSelected = true
      this.selected = item
    },
    transferRender (item) {
      return item.label + ' - ' + item.key
    },
    handleChange (newTargetKeys, direction, moveKeys) {
      // console.log('change', newTargetKeys, this.allMenus.length)
      this.targetKeys = newTargetKeys
    },
    createTableData (menuAll) {
      let vos = []
      for (let i = 0; i < menuAll.length; i++) {
        let mvo = menuAll[i]
        vos.push({key: mvo.id, label: mvo.name, sort: mvo.sort})
        if (mvo.children.length > 0) {
          for (let j = 0; j < mvo.children.length; j++) {
            vos.push({key: mvo.children[j].id, label: mvo.name + '>' + mvo.children[j].name, sort: mvo.children[j].sort})
          }
        }
      }
      return vos
    },
    onOkFunc (name) {
      this.$refs[name].validate((valid) => {
        valid = true
        if (valid) {
          let s = []
          if (!this.hasChangeSelected) {
            this.selected = this.selected.concat(this.defalutSelected)
          }
          if (this.selected) {
            this.selected.map(item => {
              s.push(item.id)
            })
          }
          let gName = this.newGroupName
          let menuIds = this.targetKeys.join(',')
          let opts = s.join(',')
          if (parseInt(this.type) === 0) {
            if (this.newGroupId > 0) {
              if (this.newGroupName.length <= 0) {
                this.$Message.error('用户组名不能为空')
                return
              }
              modifyUserGroup(this.newGroupId, gName, menuIds, opts).then((data) => {
                if (!data) {
                  return
                }
                let pv = data.data.data
                let success = pv.intValues[0]
                // console.log('delUserGroup', success, gid)
                if (success === 1) {
                  // console.log('修改成功')
                  this.$Message.info('修改成功')
                }
                this.$emit('closeEditGroupModal')
              }).catch(console.log('catch'))
            }
            // console.log('this.newGroupName', this.newGroupName, s)
          } else {
            if (this.newGroupName.length <= 0) {
              this.$Message.error('用户组名不能为空')
              return
            }

            let MGroupVO = getVO('MGroupVO')
            var mGroupVO = new MGroupVO()
            mGroupVO.gid = 0
            mGroupVO.gName = gName
            mGroupVO.except = menuIds
            mGroupVO.exceptAction = opts
            addUserGroup(mGroupVO).then((data) => {
              if (!data) {
                return
              }
              let pv = data.data.data
              let success = pv.intValues[0]
              // let gid = pv.longValues[0].toNumber()
              // console.log('addUserGroup', success, gid)
              if (success === 1) {
                this.$Message.info('增加成功')
                // this.tableData.push({
                //   gid: gid, gName: gName, except: gids
                // })
              }
              this.$emit('closeEditGroupModal')
            })
          }
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },
    onCancelFunc () {
      this.$emit('closeEditGroupModal')
    }
  },
  computed: {
    getShowModal () {
      console.log('show', this.getGroupId, this.type)
      if (this.showModal) {
        this.targetKeys = this.getTargetKeys
        this.allOpreates = this.getOpreates
        this.newGroupName = this.oldGroupName
        this.newGroupId = this.getGroupId
        // this.selected = []
        // if (this.allOpreates) {
        //   this.allOpreates.map(item => {
        //     if (this.oldGroupPowers.indexOf(item.id) >= 0) {
        //       this.selected.push(item)
        //     }
        //   })
        // }
      }
      return this.showModal
    },
    getTitle () {
      return parseInt(this.type) === 1 ? '新建用户组' : '修改用户组'
    },
    getTargetKeys () {
      let keys = []
      if (this.allMenus) {
        keys = this.allMenus.filter((item) => this.oldGroupMenus.indexOf(item.key) >= 0).map(item => item.key)
      }
      // console.log('key', keys)
      return keys
    },
    getOpreates () {
      let opts = []
      this.defalutSelected = []
      if (this.allOpreates) {
        this.allOpreates.map(item => {
          if (this.oldGroupPowers.indexOf(item.id) >= 0) {
            item['_checked'] = true
            this.defalutSelected.push(item)
          }
          opts.push(item)
        })
      }
      // console.log('opts', opts)
      return opts
    },
    getGroupName () {
      this.newGroupName = this.oldGroupName
      return this.newGroupName
    },
    getGroupId () {
      this.newGroupId = this.oldGroupId
      return this.newGroupId
    }
  }
}
</script>

<style>
.right-table{
  float: right;
}
.left-table{
  float: left;
}
</style>
